package com.ai.ubssapp.util;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.ai.ubssapp.constant.Configs;
import com.ai.ubssapp.constant.Constants;

/**
 * httpclient工具类
 * 
 */
@Component
@SuppressWarnings("serial")
public class BizHttpClientHelper {
	
	protected Logger log = LoggerFactory.getLogger(BizHttpClientHelper.class);
	
	@Resource(name = "configs")
	private Configs configs;
	
	/**
	 * cBSS接口地址
	 */
	@Value("${intf.cbss}")
	private String serviceHost;
	
	/**
	 * 退出cas 接口url
	 */
	@Value("${service.cas.logout.addr}")
	private String casLogoutAddr;

	/**
	 * 一点退出所有系统
	 * 
	 * @param loginParam
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public boolean logoutAll(String loginParam) throws Exception {
		String deLoginParam = java.net.URLDecoder.decode(parseLoginParam(loginParam), Constants.CHARSET_UTF8);
		String castgc = HttpRequestParser.parse("?" + deLoginParam).getParameter("_castgc");

		// 1、退出cBSS 暂未实现，屏蔽
		// logoutCbss(castgc);

		// 2、退出BSS 暂未实现，屏蔽
		// logoutBss(castgc);

		// 3、退出cas
		logoutCas(castgc);

		return true;
	}
	
	/**
	 * 退出cas
	 * 
	 * @param castgc
	 * @return
	 * @throws Exception
	 */
	private boolean logoutCas(String castgc) throws Exception {
//		String serviceHost = HttpRequstUtil.getCbssIntfHost();
//		String casLogoutAddr = Common.getInstance().getProperty("service/cas/logout/addr");
		String casLooutUrl = serviceHost + casLogoutAddr;
		HttpClientContext context = HttpClientContext.create();
		BasicCookieStore cookieStore = new BasicCookieStore();
		BasicClientCookie cookie = new BasicClientCookie(Constants.CASTGC_COOKIE_NAME, castgc);// 基于cas的登陆必须在这设置castgc
		cookie.setDomain(getDomainFromUrl(casLooutUrl));
		cookie.setPath("/");
		cookieStore.addCookie(cookie);
		context.setCookieStore(cookieStore);

		try {
			logoutPost(casLooutUrl, context);
		} catch (Exception e) {
			log.error("cas退出失败！", e);
			return false;
		}

		return true;
	}
	
	/**
	 * 发起退出请求
	 * 
	 * @param url
	 * @param context
	 * @return
	 * @throws Exception
	 */
	private String logoutPost(String url, HttpClientContext context) throws Exception {
		String responseBody = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader("Referer", url);
		try {
			responseBody = httpclient.execute(httppost, getResponseHandler(), context);
		} finally {
			httpclient.close();
		}
		return responseBody;
	}
	
	/**
	 * 获取域
	 * 
	 * @param url
	 * @return
	 * @throws MalformedURLException
	 */
	private String getDomainFromUrl(String url) throws MalformedURLException {
		return new URL(url).getHost();
	}
	
	/**
	 * 解析loginParam
	 * 
	 * @param loginParam
	 * @return
	 * @throws Exception
	 */
	public String parseLoginParam(String loginParam) throws Exception {
		return EncryptUtil.decryptByDES(loginParam, configs.securityKey);
	}
	
	/**
	 * 获取handler
	 * 
	 * @param charset
	 * @return
	 */
	public ResponseHandler<String> getResponseHandler() {
		return getResponseHandler(Constants.CHARSET_GBK);
	}
	
	/**
	 * 获取字符编码的handler
	 * 
	 * @param charset
	 * @return
	 */
	public ResponseHandler<String> getResponseHandler(String charset) {
//		ResponseHandler<String> handler = ResponseHandlerSet.CHARSET_HANDLER.get(charset);
//		handler = null == handler ? new CharsetResponseHandler(charset) : handler;
		
		ResponseHandler<String> handler = new CharsetResponseHandler(charset);
		return handler;
	}
	
	
	/**
	 * <p>获取请求参数</p>
	 * <p>修改记录：<br/>
	 *    1. 修改内容：增加兼容list/object[]类型参数传递，传递同名参数 
	 * </p>
	 * 
	 * @param params
	 * @return
	 */
	public List<NameValuePair> getPostParam(Map<String, Object> params) {
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		if (params != null) {
			Object value = null;
			for (String key : params.keySet()) {
				value = params.get(key);
				if (value instanceof Object[]) {
					for (Object obj : (Object[])value) {
						nvps.add(new BasicNameValuePair(key, getString(obj)));
					}
				} else if (value instanceof List) {
					for (Object obj : (List<?>)value) {
						nvps.add(new BasicNameValuePair(key, getString(obj)));
					}
				} else {
					nvps.add(new BasicNameValuePair(key, getString(value)));
				}
			}
		}
		return nvps;
	}	
	
	/**
	 * <p>获取非空字符串</p>
	 * 
	 * @param obj
	 * @return
	 */
	private static String getString(Object obj) {
		return null == obj ? "" : obj.toString();
	}
}
